﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using LY.Common.Utils.Sf_Struct;
using LY.ShengPayApi.Model;
using Newtonsoft.Json;


namespace LY.ShengPayApi.Services
{
    public class Put
    {
        /// <summary>
        /// 平台发债权标 这个暂时没有使用这里的方法
        /// </summary>
        /// <param name="merchantNo">平台商户号（由盛付通分配，请联系盛付通商务获取）</param>
        /// <param name="issueBidNo">平台发标编号（由平台生成，并在平台中保证唯一）</param>
        /// <param name="debitUserName">平台用户账户（当issueBidType=1时，该字段必填）（由平台生成，并在平台中保证唯一）</param>
        /// <param name="debitAmount">借款总金额（以元为单位，仅允许两位小数。譬如：600.00）</param>
        /// <param name="revenueRate">年化收益率（以百分比为单位，仅允许两位小数。譬如：20.79）</param>
        /// <param name="deadline">借款期限（以天为单位，仅允许自然数，例如365）</param>
        /// <param name="apiAddress">盛付通API地址</param>
        /// <returns></returns>
        public static string FaZhaiQuan(string merchantNo, string issueBidNo, string debitUserName, string debitAmount, string revenueRate, string deadline,string apiAddress)
        {
            string[] mysign = new string[9];
            mysign[0] = "merchantNo=" + merchantNo;
            mysign[1] = "issueBidNo=" + issueBidNo;//标号 不会重复
            mysign[2] = "issueBidType=1";//发标类型 目前只能是1而且不建议用商户号，避免融资
            mysign[3] = "debitUserName=" + debitUserName; //这里发债权标的时候，都是已商户的名义发的，但是目前位置只能发个人标
            mysign[4] = "debitAmount=" + debitAmount;//借款总金额
            mysign[5] = "revenueRate=" + revenueRate;//年化收益率
            mysign[6] = "deadline=" + deadline; 
            mysign[7] = "repaymentMode=2";//还款方式 按月付息，到期还本
            mysign[8] = "rewardAmount=0.00";  //酬劳金额
            Array array = mysign;
            Array.Sort(array);
            string sign = string.Join("&", mysign);
            string temp = new MySign().GetSign(sign);
            string newsign = HttpContext.Current.Server.UrlEncode(temp);
            WebClient webClient = new WebClient();//p2pBid/{merchantNo}-{issueBidNo} 
            // 要提交表单的URI字符串。
            string postString = sign + "&sign=" + newsign;
            byte[] postData = Encoding.UTF8.GetBytes(postString);//编码，尤其是汉字，事先要看下抓取网页的编码方式
            string url = apiAddress + "/p2pBid/" + merchantNo + "-" + issueBidNo + postString;
            byte[] responseData = webClient.UploadData(url, "PUT", postData);//得到返回字符流 
            return Encoding.UTF8.GetString(responseData);
        }


        /// <summary>
        /// 平台满标-流标
        /// </summary>
        /// <param name="merchantNo">平台商户号（由盛付通分配，请联系盛付通商务获取）</param>
        /// <param name="issueBidNo">平台发标编号（由平台生成，并在平台中保证唯一）</param>
        /// <param name="eventType">事件类型</param>
        /// <param name="notifyUrl">异步通知回调地址</param>
        /// <param name="platformFee">支付给平台的手续费（当eventType=2时，该字段必填）（以元为单位，仅允许两位小数。譬如：600.00）</param>
        /// <param name="apiAddress"></param>
        /// <returns></returns>
        public static string PutP2PBidEvent(string merchantNo, string issueBidNo, int eventType, string notifyUrl, string platformFee, string apiAddress)
        {
            WebClient webClient = new WebClient();
            if (eventType == 1) //流标
            {
                string[] mysign = new string[4];
                mysign[0] = "merchantNo=" + merchantNo;
                mysign[1] = "issueBidNo=" + issueBidNo;
                mysign[2] = "eventType=1";
                mysign[3] = "notifyUrl=" + notifyUrl;
                Array array = mysign;
                Array.Sort(array);
                string sign = string.Join("&", mysign);
                string temp = new MySign().GetSign(sign);
                string newsign = HttpContext.Current.Server.UrlEncode(temp);
                string postString = sign + "&sign=" + newsign;
                byte[] postData = Encoding.UTF8.GetBytes(postString);//编码，尤其是汉字，事先要看下抓取网页的编码方式
                string url = apiAddress + "/p2pBid/" + merchantNo + "-" + issueBidNo + "/event?" + postString;
                byte[] responseData = webClient.UploadData(url, "PUT", postData);//得到返回字符流 
                return Encoding.UTF8.GetString(responseData);
            }
            else//满标
            {
                string[] mysign = new string[6];
                mysign[0] = "merchantNo=" + merchantNo;
                mysign[1] = "issueBidNo=" + issueBidNo;
                mysign[2] = "eventType=2";
                mysign[3] = "platformFee=" + platformFee;
                mysign[4] = "notifyUrl=" + notifyUrl;
                mysign[5] = "dealerFee=0.00";
                Array array = mysign;
                Array.Sort(array);
                string sign = string.Join("&", mysign);
                MySign mySign = new MySign();
                string temp = mySign.GetSign(sign);
                int a = temp.Length;
                
                //string newsign = System.Web.HttpUtility.HtmlEncode(temp);
                string newsign = HttpContext.Current.Server.UrlEncode(temp);
                string postString = "?dealerFee=0.00&eventType=2&notifyUrl=" + notifyUrl + "&platformFee=" + platformFee + "&sign=" + newsign; 
                byte[] postData = Encoding.UTF8.GetBytes(postString);//编码，尤其是汉字，事先要看下抓取网页的编码方式
                string url = apiAddress + "/p2pBid/" + merchantNo + "-" + issueBidNo + "/event" + postString;
                byte[] responseData = webClient.UploadData(url, "PUT", postData);//得到返回字符流 
                return Encoding.UTF8.GetString(responseData);
            }
        }

        //通用还款
        public static string TongYongHuanKuan()
        {
            //string[] mysign = new string[9];
            //mysign[0] = "merchantNo=" + merchantNo;
            //mysign[1] = "issueBidNo=" + issueBidNo;//标号 不会重复
            //mysign[2] = "issueBidType=1";//发标类型 目前只能是1而且不建议用商户号，避免融资
            //mysign[3] = "debitUserName=" + debitUserName; //这里发债权标的时候，都是已商户的名义发的，但是目前位置只能发个人标
            //mysign[4] = "debitAmount=" + debitAmount;//借款总金额
            //mysign[5] = "revenueRate=" + revenueRate;//年化收益率
            //mysign[6] = "deadline=" + deadline;
            //mysign[7] = "repaymentMode=2";//还款方式 按月付息，到期还本
            //mysign[8] = "rewardAmount=0.00";  //酬劳金额
            //Array array = mysign;
            //Array.Sort(array);
            //string sign = string.Join("&", mysign);
            //string temp = new MySign().GetSign(sign);
            //string newsign = System.Web.HttpUtility.HtmlEncode(temp);
            //WebClient webClient = new WebClient();//p2pBid/{merchantNo}-{issueBidNo} 
            //// 要提交表单的URI字符串。
            //string postString = sign + "&sign=" + newsign;
            //byte[] postData = Encoding.UTF8.GetBytes(postString);//编码，尤其是汉字，事先要看下抓取网页的编码方式
            //string url = apiAddress + "/p2pBid/" + merchantNo + "-" + issueBidNo + postString;
            //byte[] responseData = webClient.UploadData(url, "PUT", postData);//得到返回字符流 
            //return Encoding.UTF8.GetString(responseData);
            return null;
        }

        /// <summary>
        /// 用户投标（自动）
        /// </summary>
        /// <param name="serverUrl">服务地址</param>
        /// <param name="merchantNo">商户号</param>
        /// <param name="project">参数</param>
        /// <returns>json字符串</returns>
        public static string PutP2PBid(string serverUrl, string merchantNo,ZCProject project)
        { 
           string[] mysign = new string[11];
           mysign[0] = "merchantNo=" + merchantNo;
           //标号 不会重复
           mysign[1] = "issueBidNo=" + project.BiaoNo;
           //发标类型 目前只能是1 应为如果是商户发标的话 就要一个商户号了，而现在的测试商户号 不能作为发标的商户号
           mysign[2] = "issueBidType=1";
           //发标机构商户号
           //System.Web.HttpContext.Current.Session["LoginUseInfo"]
           mysign[3] = "debitUserName=" + project.SFTUserName;
           //担保机构商户号 
           //mysign[4] = "guarantorMerchantNo=708732";
           //借款总金额
           mysign[4] = "debitAmount=" + Math.Round((decimal)project.Amount, 2);
           //年化收益率 这里是众筹，所以没有
           mysign[5] = "revenueRate=0.01";
           //还款方式 按月付息，到期还本
           //mysign[8] = "repaymentMode=2";
           //是否是直销模式 否
           //mysign[9] = "directSelling=2";
           //酬劳金额
           mysign[6] = "rewardAmount=0.00";
           //借款日期
           mysign[7] = "deadline=" + project.CollectDays;
           //是否使用分润模式 否
           //mysign[11] = "profitMode=2";
           //交易类型 众筹
           mysign[8] = "tradeType=2";
           //筹款项目名称
           mysign[9] = "projectName=" + project.ProjectName;
           mysign[10] = "loanMode=1";

           //关联订单号
           //mysign[13] = "associatedOrderNo=" + project.ProjectNo;
           Array array = mysign;
           Array.Sort(array);
           //mysign = (string[])array;
           string sign = string.Join("&", mysign);
           MySign mySign = new MySign();
           //获得签名。封装号的方法
           string temp = mySign.GetSign(sign);
           string newsign = HttpContext.Current.Server.UrlEncode(temp);

           string postString = "?issueBidType=1&debitUserName=" + project.SFTUserName + "&debitAmount=" +
                               Math.Round((decimal) project.Amount, 2) +
                               "&revenueRate=" + "0.01" + "&deadline=" + project.CollectDays + "&rewardAmount=0.00" +
                               "&tradeType=2" + "&projectName=" + project.ProjectName + "&loanMode=1"+
               "&sign=" + newsign;
             
           string url = serverUrl + "/p2pBid/" + merchantNo + "-" + project.BiaoNo + postString;

          return  HttpPut(url, postString);
      
       } 


         
       /// <summary>
       ///  平台分批放款接口
       /// </summary>
       /// <param name="serverUrl"></param>
       /// <param name="merchantNo"></param> 
       /// <param name="backAddress"></param>
       /// <param name="project"></param>
       /// <returns></returns>
       public static string PutLoan(string serverUrl, string merchantNo, string backAddress, ZCProjectLoan project)
       { 
               string[] mysign = new string[9];
               //平台商户号
               mysign[0] = "merchantNo=" + merchantNo; 
               mysign[1] = "origOrderType=1";
               mysign[2] = "origOrderNo=" + project.BiaoNo;
               mysign[3] = "loanNo=" + project.LoanNo;
               mysign[4] = "loanAmount=" + project.LoanAmount;
               mysign[5] = "platformFee=" + project.PlatformFee;
               mysign[6] = "dealerFee=" + project.DealerFee;
               //异步通知地址
               mysign[7] = "notifyUrl=" + backAddress + "/Pay/LoanNotifyUrl";  
               mysign[8] = "timestamp=" + DateTime.Now.ToString("yyyyMMddHHmmss"); 
             
               Array array = mysign;
               Array.Sort(array);
               string sign = string.Join("&", mysign);
               MySign mySign = new MySign();
               //获得签名。封装号的方法
               string temp = mySign.GetSign(sign);
               string newsign = HttpContext.Current.Server.UrlEncode(temp);
               // 初始化WebClient 
          
               //string postString = "?origOrderType=1&notifyUrl=" + backAddress + "/Pay/LiuBiaoNotifyUrl" + "&sign=" + newsign;
               string postString = "?" + string.Join("&", mysign) + "&sign=" + newsign;
               string url = serverUrl + "/loan/" + merchantNo + "-" + project.LoanNo + postString;

               return HttpPut(url, postString);
 
       }


       private static string HttpPut(string url, string param)
       {
           var webClient = new WebClient();
         //  webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
           byte[] postData = Encoding.ASCII.GetBytes(param);
           // 上传数据，返回页面的字节数组
           byte[] responseData = webClient.UploadData(url, "PUT", postData);
           // 返回的将字节数组转换成字符串(HTML)
           return Encoding.UTF8.GetString(responseData);
       }

    }
}
